#region license
/*
 * Copyright (C) 2007 CchenSoft.com
 * 
 * This library is free software; you can redistribute it and/or modify it 
 * under the terms of the GNU Lesser General Public License 2.1 or later, as
 * published by the Free Software Foundation. See the included License.txt
 * or http://www.gnu.org/copyleft/lesser.html for details.
 * 
 * Author: Billy Zhang
 */
#endregion

using System;
using System.Collections.Generic;
using System.Text;
using CchenSoft.Portal.Model;
using CchenSoft.Portal.Registry;
using System.Web;
using CchenSoft.Portal.Web;
using CchenSoft.Portal.Service;

namespace CchenSoft.Portal
{
    public class PortalContext
    {
        private const string CONTEXT_KEY = "portal.context";

        private PortalPage page;
        private PortalURL url;
        private LayoutTemplate layout;
        private Theme theme;
        private IList<PortletInstance> portlets;
        private IList<Producer> producers;
        private User user;
        private bool isAdmin;

        public PortalContext(PortalPage page, PortalURL url, HttpContext httpCtx)
        {
            this.page = page;
            this.url = url;
            portlets = new List<PortletInstance>();
            producers = new List<Producer>();
            layout = LayoutRegistry.Instance.GetLayoutTemplate(page.LayoutId);
            theme = ThemeRegistry.Instance.GetTheme(page.ThemeId);
            user = ServiceLocator.UserService.LoggedUser;
            isAdmin = (user != null) ? (user.UserId == page.UserId || (page.UserId == 0 && user.IsAdmin)) : (false);
            httpCtx.Items[CONTEXT_KEY] = this;
        }

        public static PortalContext Current
        {
            get { return (PortalContext)HttpContext.Current.Items[CONTEXT_KEY]; }
        }

        public User User
        {
            get { return user; }
        }

        public bool IsAdmin
        {
            get { return isAdmin; }
        }

        public PortalPage PortalPage
        {
            get { return page; }
        }

        public PortalURL PortalURL
        {
            get { return url; }
        }

        public LayoutTemplate Layout
        {
            get { return layout; }
        }

        public Theme Theme
        {
            get { return theme; }
        }

        public void AddPortlet(PortletInstance portlet)
        {
            portlets.Add(portlet);
        }

        public IList<Producer> Producers
        {
            get { return new List<Producer>(producers); }
        }

        public void AddProducer(Producer producer)
        {
            producers.Add(producer);
        }
    }
}
